package com.xincheng.shuimalong.activity.insurance;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.adapter.friend.ChatAdapter;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.entity.friend.ChatMessage;
import com.xincheng.shuimalong.entity.friend.Friend;
import com.xincheng.shuimalong.listener.OnMessageListener;
import com.xincheng.shuimalong.util.GreenUtil;
import com.xincheng.shuimalong.util.RongUtil;
import com.xincheng.shuimalong.view.EmojiUtil;
import com.xincheng.shuimalong.view.KeyboardLayout;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;

import static com.xincheng.shuimalong.view.KeyboardLayout.KEYBOARD_STATE_HIDE;
import static com.xincheng.shuimalong.view.KeyboardLayout.KEYBOARD_STATE_SHOW;


/**
 * Created by 许浩 on 2017/7/1.
 */

public class ChatActivity extends BaseActivity implements TextView.OnEditorActionListener {
    @BindView(R.id.chat_listview)
    ListView chatListview;
    @BindView(R.id.ib_audio)
    ImageButton ibAudio;
    @BindView(R.id.et_chat)
    EditText etChat;
    @BindView(R.id.imb_face)
    ImageButton imbFace;
    @BindView(R.id.ib_send_img)
    ImageButton ibSendImg;
    @BindView(R.id.ll_expand)
    LinearLayout llExpand;
    @BindView(R.id.chat_bottom_layout)
    KeyboardLayout chatBottomLayout;
    private List<ChatMessage> infolist;
    private ChatAdapter adapter;
    private String targetId;
    private String content = "";
    private Friend.Data friend;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_chat_layout;
    }

    @Override
    public void initData() {
        infolist = new ArrayList<>();
        adapter = new ChatAdapter(getContext(), infolist);
        chatListview.setAdapter(adapter);
        EmojiUtil emojiUtil = new EmojiUtil(this);
        llExpand.addView(emojiUtil.getEmojiView());
        emojiUtil.setOnItemClickListener(new EmojiUtil.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == parent.getAdapter().getCount() - 1) {
                    etChat.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
                } else {
//                    int emoji = (Integer) parent.getItemAtPosition(position);
//                    int selection = etChat.getSelectionStart();
//                    StringBuilder sb = new StringBuilder();
//                    sb.append(content.substring(0, selection)).append(emoji).append(content.substring(selection, content.length()));
//                    etChat.setText(EditTextUtil.getContent(getContext(),sb.toString()));
//                    etChat.setSelection(selection + emoji.length());
                }
            }
        });
        Bundle bundle = getIntent().getExtras();
        friend = (Friend.Data) bundle.getSerializable(IntentKey.FRIEND_BEAN);
        if (friend != null) {
            targetId = friend.getUser_id();
            initTitleBar(friend.getNick_name());
            RongIMClient.getInstance().getConversation(Conversation.ConversationType.PRIVATE,
                    targetId,
                    new RongIMClient.ResultCallback<Conversation>() {
                        @Override
                        public void onSuccess(Conversation conversation) {
                            if (conversation != null) {
                                getHistory(conversation);
                            }
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {
                            XLog.e(errorCode);
                        }
                    }
            );
        }
        setResult(RESULT_OK);
    }

    private void getHistory(Conversation conversation) {
        int per_page = -1;
        int lastmessageid = conversation.getLatestMessageId() + 1;
        if (lastmessageid != 1) {
            per_page = 20;
        }
        targetId = conversation.getTargetId();
        RongIMClient.getInstance().getHistoryMessages(Conversation.ConversationType.PRIVATE
                , targetId
                , lastmessageid,
                per_page,
                new RongIMClient.ResultCallback<List<Message>>() {
                    @Override
                    public void onSuccess(List<Message> messages) {
                        if (messages != null) {
                            for (Message message : messages) {
                                if (message.getContent() instanceof ChatMessage) {
                                    infolist.add(0, (ChatMessage) message.getContent());
                                }
                            }
                            adapter.notifyDataSetChanged();
                            scrollMyListViewToBottom();
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                }
        );
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            ChatMessage chatMessage= (ChatMessage) msg.obj;
            infolist.add(chatMessage);
            adapter.notifyDataSetChanged();
            scrollMyListViewToBottom();
        }
    };
    @Override
    public void addListener() {
        etChat.setOnEditorActionListener(this);
        etChat.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                content = s.toString().trim();
            }
        });
        RongUtil.getInstances().setMessageListener(new OnMessageListener() {
            @Override
            public void onMessage(ChatMessage message, int left) {
                if(message.getFrom().equals(targetId)){
                    //是该回话添加到消息
                    android.os.Message msg=new android.os.Message();
                    msg.what=1;
                    msg.obj=message;
                    handler.sendMessage(msg);
                }
            }
        });
//        chatBottomLayout.setOnkbdStateListener(new KeyboardLayout.onKybdsChangeListener() {
//            @Override
//            public void onKeyBoardStateChange(int state) {
//                switch (state) {
//                    case KEYBOARD_STATE_HIDE:
//                        etChat.setFocusable(false);
//                        etChat.setFocusableInTouchMode(false);
//                        break;
//                    case KEYBOARD_STATE_SHOW:
//                        etChat.setFocusable(true);
//                        etChat.setFocusableInTouchMode(true);
//                        llExpand.setVisibility(View.GONE);
//                        chatListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
//                        break;
//                }
//            }
//        });
    }
    private void scrollMyListViewToBottom() {
        chatListview.post(new Runnable() {
            @Override
            public void run() {
                // Select the last row so it will scroll into view...
                chatListview.setSelection(adapter.getCount() - 1);
            }
        });
    }
    @OnClick({R.id.ib_audio, R.id.imb_face, R.id.ib_send_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_audio:
                showToast("语音聊天");
                break;
            case R.id.imb_face:
                imbFace.setSelected(!imbFace.isSelected());
                if (imbFace.isSelected()) {
                    llExpand.setVisibility(View.VISIBLE);
                } else {
                    llExpand.setVisibility(View.GONE);
                }
                break;
            case R.id.ib_send_img:
                showToast("图片");
                break;
        }
    }

    private void SendMessage(String message) {
        ChatMessage textMessage = new ChatMessage();
        textMessage.setMsg_type(0);
        textMessage.setContent(message);
        textMessage.setTime(new Date().getTime());
        textMessage.setNickname(PrefUtil.getString(getContext(), PrefKey.LOGIN_NICKNAME, ""));
        textMessage.setFace(PrefUtil.getString(getContext(), PrefKey.LOGIN_FACE, ""));
        textMessage.setFrom(PrefUtil.getString(getContext(), PrefKey.LOGIN_USER_ID, ""));
        textMessage.setTo(targetId);
        textMessage.setUserInfo(new UserInfo(
                PrefUtil.getString(getContext(), PrefKey.LOGIN_USER_ID, ""),
                PrefUtil.getString(getContext(), PrefKey.LOGIN_NICKNAME, ""),
                Uri.parse(PrefUtil.getString(getContext(), PrefKey.LOGIN_FACE, ""))));
        RongIMClient.getInstance().sendMessage(Conversation.ConversationType.PRIVATE,
                targetId,
                textMessage,
                "您有一条新消息",
                textMessage.toString(),
                new IRongCallback.ISendMessageCallback() {
                    @Override
                    public void onAttached(Message message) {
                        // 消息成功存到本地数据库的回调
                    }

                    @Override
                    public void onSuccess(Message message) {
                        // 消息发送成功的回调
                        etChat.setText("");
                        infolist.add((ChatMessage) message.getContent());
                        adapter.notifyDataSetChanged();
                        scrollMyListViewToBottom();
                    }

                    @Override
                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                        // 消息发送失败的回调
                        XLog.e(message);
                        XLog.e(errorCode);
                    }
                });
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            System.out.println("action send for : " + v.getText());
            SendMessage(v.getText().toString());
        }
        return false;
    }
    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (friend != null && infolist.size() > 0) {
            ChatMessage chatMessage = infolist.get(infolist.size() - 1);
            GreenUtil.getInstances().updaConversation(friend.getNick_name(), friend.getFace(), targetId, chatMessage.getTime(), chatMessage.getContent(), 0);
        } else if (friend != null && infolist.size() == 0) {
            GreenUtil.getInstances().deleteHisory(targetId);
        }
        RongUtil.getInstances().setMessageListener(null);
    }
}
